﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Xml;
using System.Windows.Forms;
using System.Resources;

namespace ApplicationLibrary.DBManager
{
    class ThemeManager
    {
        private static Dictionary<string, ThemeStorage> theme = new Dictionary<string, ThemeStorage>();
        private static ResourceManager rm = Properties.Resources.ResourceManager;

        public static void SetTheme(object resource)
        {
            if (GlobalInfo.globalPref == null || !GlobalInfo.globalPref.CustmColor)
                return;

            if (theme.Count == 0)
                LoadThemes();

            if ((resource.GetType().BaseType.Equals(typeof(DocumentForm)) ||
                resource.GetType().BaseType.BaseType.Equals(typeof(DocumentForm))) &&
                theme.ContainsKey("DocumentForm"))
            {
                ((DocumentForm)resource).BackColor = theme["DocumentForm"].BackColor;
            }

            if (resource.GetType().BaseType.Equals(typeof(ToolStrip)) &&
                theme.ContainsKey("ToolStrip"))
            {
                ((ToolStrip)resource).BackgroundImage = theme["ToolStrip"].BackgroundImage;
                ((ToolStrip)resource).BackgroundImageLayout = ImageLayout.Stretch;
            }
        }

        private static void LoadThemes()
        {
            XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml(Properties.Resources.Themes);
            XmlNode xNode = xDoc.SelectSingleNode("//Theme[@name='blue']");
            foreach (XmlNode xNd in xNode.ChildNodes)
            {
                string name = xNd.Name;
                theme.Add(name, new ThemeStorage());
                foreach (XmlNode xProp in xNd.ChildNodes)
                {
                    if (xProp.Name == "BackColor")
                        theme[name].BackColor = DecodeColor(xProp.InnerText);
                    if (xProp.Name == "BackgroundImage")
                    {
                        theme[name].BackgroundImage = (Image)rm.GetObject(xProp.InnerText);
                    }
                }
            }
        }

        private static Color DecodeColor(string val)
        {
            string[] col = val.Split(',');
            return Color.FromArgb(int.Parse(col[0]), int.Parse(col[1]), int.Parse(col[2]));
        }
    }

    internal class ThemeStorage
    {
        public Color BackColor;
        public Image BackgroundImage;
    }
}
